import requests
import re
import os
import time,math
import urllib3
import webtool
import json


class Pixiv_Picture:
    def __init__(self,pid = "67994735",name = "67994735.jpg"):
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
        self.name = name
        self.pid = pid
        self.url = "https://www.pixiv.net/artworks/"+pid
        self.picurls = []
        self.r = None
        self.headers = webtool.MY_HEADERS
        
        print(f"新建pixiv图片对象:pid = {self.pid},url = {self.url}")


    def download(self):
        self.get_pixivpic_url()
        self._pic_download()

    def get_pixivpic_url(self):
        self.r = requests.get(url=self.url, headers=self.headers, verify=False)
        self.picurls = re.findall( "https://i.pximg.net/img-original/img/[^\"]*",self.r.text)

        if len(self.picurls) == 0:
            retxt = re.compile(r"img.{16,30}%s.{0,20}\.jpg" % self.pid)
            self.picurls = retxt.findall(self.r.text)
            if len(self.picurls) != 0:
                time_text = re.search(r"/\d{4}/\d{2}/\d{2}/\d{2}/\d{2}/\d{2}/",self.picurls[0])
                self.picurls = [f"https://i.pximg.net/img-original/img{time_text[0]}{self.pid}_p0.jpg"]              
        
        print("本系列图片共有%d张" % len(self.picurls))
        for picurl in self.picurls:
            print(picurl)

    def _print_text(self):
        print(self.r.text)

    def _pic_download(self):
        i=1
        time.sleep(4)
        if(self.picurls):
            for picurl in self.picurls:
                pic_type = picurl[-3:]
                if(pic_type == "png" or pic_type == "jpg"):
                    print(f"正在下载第{i}张图片")
                    try:
                        pic = requests.get(url=picurl, headers=self.headers, verify=False)
                        if i<10:
                            num = f"p0{i}"
                        else:
                            num = f"p{i}"
                        if not os.path.exists("pixiv原图"):
                            os.makedirs("pixiv原图")  # 使用os.makedirs()方法创建多层目录
                        filename = self.name[:-4] +"_原图_" + num
                        with open(f"pixiv原图/{filename[:-4]}.{pic_type}", "wb") as f:
                            f.write(pic.content)
                            print(f"第{i}图片下载成功")
                    except:
                        print(f"第{i}图片下载失败")
                    i+=1
                else:
                    print("图片类型错误")
        else:
            print("url为空")


class Pixiv_Piclist:
    def __init__(self):
        self.piclist = []
        self.thislist = []
    
    def writelist(self, piclist:list):
        self.piclist = piclist
        self.thislist = piclist
        with open("pixiv_list_js.txt","w+") as f:
            json.dump(self.piclist, f)
            f.close()
            
    def readlist(self, num = 0):
        with open("pixiv_list_js.txt","r") as f:
            self.piclist = json.load(f)
            f.close()
            this_piclist = self.piclist[num:]
        return this_piclist
    
    def printwholelist(self):
        self.readlist()
        print("已存储%d张图片的信息:" % len(self.piclist))
        for pic in self.piclist:
            print(pic["pic_name"]+" = "+pic["illust_id"])
        print("")
        
    def printthislist(self, num = 0):
        self.thislist = self.readlist(num = num)
        print(f"已下载{num}张图片，剩余{len(self.thislist)}张图片:")
        for pic in self.thislist:
            print(pic["pic_name"]+" = "+pic["illust_id"])
        print("")
    
    

if __name__ == '__main__':
    ppl = Pixiv_Piclist()
    ppl.printwholelist()
    ppl.printthislist(num = 2)
    



